package com.bawei.module_wide.view.activity

import android.util.Log
import android.view.SurfaceView
import android.view.View
import android.widget.FrameLayout
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.module_base.net.util.MMKVUtil
import com.bawei.module_base.ui.base.BaseActivity
import com.bawei.module_wide.R
import com.bawei.module_wide.databinding.ActivityWatchBinding
import com.bawei.module_wide.viewmodel.WideViewModel
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.shuyu.gsyvideoplayer.GSYVideoManager
import io.agora.rtc2.ChannelMediaOptions
import io.agora.rtc2.Constants
import io.agora.rtc2.IRtcEngineEventHandler
import io.agora.rtc2.RtcEngine
import io.agora.rtc2.RtcEngineConfig
import io.agora.rtc2.video.VideoCanvas

@Route(path = "/wide/watch_activity")
class WatchActivity : BaseActivity<WideViewModel, ActivityWatchBinding>() {
    override fun getLayout(): Int {
        return R.layout.activity_watch
    }

    override fun initData() {
        init()
        	//直播状态 1=直播中 2=录播
        val liveStatus = intent.getIntExtra("liveStatus",0)
        val liveId = intent.getIntExtra("liveId",0)//直播id
        val liveTitle = intent.getStringExtra("liveTitle")//直播标题
        if (liveStatus==1){
            Toast.makeText(this,"正在直播中~",Toast.LENGTH_SHORT).show()

        }else{
            binding.stanWatch.visibility=View.VISIBLE
            binding.localVideoViewContainerWatch.visibility=View.GONE
            binding.remoteVideoViewContainerWatch.visibility=View.GONE
            binding.stanWatch.setUp("http://10.59.9.18/live-platform/recordVideo/"+liveId,true,liveTitle)
            binding.stanWatch.startPlayLogic()
            Toast.makeText(this,"正在观看录播~",Toast.LENGTH_SHORT).show()
        }


        //检测 直播间的 观看人数
        viewModel.mPersonCount.observe(this) {
//            vdb.livePlayCountId.text= it?.num ?: "0"
            Log.e("===okhttp 观看人数", "${it.toString()}")
        }

        viewModel.dataWatchLive.observe(this){
            if ( it.status=="1001") {
                ToastUtils.showShort("这个直播有问题哦")
                finish()
                return@observe
            }
            if (it.status=="0000"){
                viewModel.channelName = it.result!!.channelName
                viewModel.agoraToken = it.result!!.agoraToken
                viewModel.compositeWsUrl = it.result!!.compositeWsUrl
            }

                viewModel.connectSocket(this)
                initializeAndJoinChannel()
            }
        }

    fun init(){
        val liveCoverUrl = intent.getStringExtra("liveCoverUrl")//	直播封面地址
        val liveTime = intent.getStringExtra("liveTime")//直播开始时间
        val channelName = intent.getStringExtra("channelName")	//声网渠道名称
        val liveId = intent.getIntExtra("liveId",0)
        val anchorId = intent.getIntExtra("anchorId",0)//主播ID
        val sex = intent.getIntExtra("sex",0)//性别 //1=男 2=女

        //设置观看数据
//        binding.liveWatchCountId.setText(watchLiveBean.result.watchNumber.toString())
        // 绑定状态 1=未绑定 2=已绑定  是否关注
        val follow = intent.getIntExtra("follow",0)//1=没关注 2=关注了
        if (follow == 1) {
            //关注 按钮显示
            binding.liveWatchSeguireBtnTrueId.visibility = View.VISIBLE
        } else {
            binding.liveWatchSeguireBtnFalseId.visibility = View.VISIBLE
            //取消关注按钮显示
        }
        val nickName = intent.getStringExtra("nickName")	//主播昵称
        binding.liveWatchUserNameId.text=nickName

        val headPic = intent.getStringExtra("headPic")//主播头像
        Glide.with(this).load(headPic).circleCrop().into(binding.liveWatchUserPicId)
    }

/**
 * 进入直播的初始化
 */
private var mRtcEngine: RtcEngine? = null
private fun initializeAndJoinChannel() {
    try {
        // 创建 RtcEngineConfig 对象，并进行配置
        val config = RtcEngineConfig()
        config.mContext = baseContext
        config.mAppId = "e394d3be4df34e1d9f8b67bc5a007de7"
        config.mEventHandler = object : IRtcEngineEventHandler() {
            // 监听频道内的远端用户，获取用户的 uid 信息
            override fun onUserJoined(uid: Int, elapsed: Int) {
                // 获取 uid 后，设置远端视频视图
                runOnUiThread {
                    viewModel.liveUid = uid
                    setupRemoteVideo(uid)
                }
                Log.e("===okhttp 监听频道内的远端用户1", "${uid}")
            }
        }
        // 创建并初始化 RtcEngine
        mRtcEngine = RtcEngine.create(config)
    } catch (e: Exception) {
        throw RuntimeException("Check the error.")
    }

    // 启用视频模块
    mRtcEngine?.enableVideo()
    // 开启本地预览
    mRtcEngine?.startPreview()

    //设置初始为观众
    //角色设置为 BROADCASTER (主播) 或 AUDIENCE (观众)
    //Constants.CLIENT_ROLE_AUDIENCE
    settingLiveType(Constants.CLIENT_ROLE_AUDIENCE, viewModel.agoraToken)
    //设置为隐藏 本地的视频
    binding.localVideoViewContainerWatch.visibility = View.GONE
}

/**
 * 设置直播类型 据场景将用户角色设置为 BROADCASTER (主播) 或 AUDIENCE (观众)
 */
fun settingLiveType(type: Int, token: String) {
    // 创建 ChannelMediaOptions 对象，并进行配置
    val options = ChannelMediaOptions()
    // 根据场景将用户角色设置为 BROADCASTER (主播) 或 AUDIENCE (观众)
    options.clientRoleType = type
    // 直播场景下，设置频道场景为 BROADCASTING (直播场景)
    options.channelProfile = Constants.CHANNEL_PROFILE_LIVE_BROADCASTING
    // 使用临时 Token 加入频道，自行指定用户 ID 并确保其在频道内的唯一性
    mRtcEngine?.joinChannel(
        token,
        viewModel.channelName,
        MMKVUtil.getUserId(),
        options
    )

}
    private fun setupRemoteVideo(uid: Int) {
        val container = findViewById<FrameLayout>(R.id.remote_video_view_container_watch)
        val surfaceView = SurfaceView(baseContext)
        surfaceView.setZOrderMediaOverlay(true)
        container.addView(surfaceView)
        // 将 SurfaceView 对象传入声网实时互动 SDK，设置远端视图
        Log.e("===okhttp 设置远端视图2", "${uid}")
        mRtcEngine?.setupRemoteVideo(
            VideoCanvas(
                surfaceView, VideoCanvas.RENDER_MODE_FIT, uid
            )
        )
    }

    override fun onDestroy() {
        super.onDestroy()
        GSYVideoManager.releaseAllVideos()
        // 停止本地视频预览
        mRtcEngine?.stopPreview()
        // 离开频道
        mRtcEngine?.leaveChannel()
        Log.e("===WatchLiveActivity", "onDestroy()")
        //退出直播
//        viewModel.getFansLiveClose()
    }
    override fun getViewModelClass(): Class<WideViewModel> {
       return WideViewModel::class.java
    }


}